import KoaRouter from "koa-router";
import Koa from "koa";
import * as Controllers from "./controllers";
import { DecoratorKey, MethodMetadata } from "./../decorators/router.metadata.decorator";

export function loadRoutes(): any[] {
    const routerResult = [];
    Object.keys(Controllers).forEach(item => {
        const router = new KoaRouter();
        const currentContainer = Controllers[item];
        const prefix = Reflect.getMetadata(DecoratorKey.Controller, currentContainer);
        if (prefix) {
            router.prefix(prefix);
        }
        const Prototype = currentContainer.prototype;
        Object.keys(Object.getOwnPropertyDescriptors(Prototype)).forEach((key) => {
            const config: MethodMetadata = Reflect.getMetadata(
                DecoratorKey.Method,
                Prototype,
                key
            );
            if (config) {
                router[config.method](config.url, async (ctx: Koa.Context, next: Koa.Next) => {
                    await config.fn(ctx, next);
                });
            }
        });
        routerResult.push(router.routes(), router.allowedMethods());
    });
    return routerResult;
}